using demo.ServiceRef;
using demo.Tool;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace demo
{
    public partial class PayMsg : Form
    {
        ServerSQL.operateSoapClient sqlServer ;//= new ServerSQL.operateSoapClient();
        OpaqueCommand cmd = new OpaqueCommand();
        private ServerSQL.OrderItem orderitem;
        UesrModel userData;
        public PayMsg()
        {
            InitializeComponent();
            button2.Visible = false;
            invokepayStateQuery = updateFromPayStateQuery;
            sqlServer = new ServerSQL.operateSoapClient();
        }
        public PayMsg(UesrModel userInfo)
        {
            InitializeComponent();
            userData = userInfo;
            button2.Visible = false;
            invokepayStateQuery = updateFromPayStateQuery;
            sqlServer = new ServerSQL.operateSoapClient();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            getOrderInfo();
        }


        public void getOrderInfo()
        {
            button2.Visible = false;
            string orderNo = this.textBox1.Text;
            orderitem = new ServerSQL.OrderItem();
            var retData = sqlServer.GetOrderMsg(orderNo);
            if (retData.code == 0)
            {
                orderitem = retData.data;
                labelhzid.Text = retData.data.patientId;
                labelName.Text = retData.data.PatientName;
                PatientIDCardNO.Text = retData.data.patientIdCardNo;
                label1Age.Text = retData.data.orderNo;
                PatientBirthday.Text = retData.data.tradeNo;
                label1.Text = retData.data.orderMoney;
                if (retData.data.IsPay == "0")
                {
                    label1Sex.Text = "未查到支付状态";
                    button2.Visible = true;
                }
                else if (retData.data.IsPay == "2")
                {
                    label1Sex.Text = "支付成功，充值失败";
                    button2.Visible = true;
                }
                else if (retData.data.IsPay == "1")
                {
                    label1Sex.Text = "充值成功";
                }

            }
        }
        int payStateRes = -1;
        public string PayStateMsg = "";

        private Thread threadpayStateQuery;
        public delegate void FormShowpayStateQuery();
        public FormShowpayStateQuery invokepayStateQuery;

        private void button2_Click(object sender, EventArgs e)
        {
            button2.Visible = false;
            cmd.ShowOpaqueLayer(this, 100, true);
            threadpayStateQuery = new Thread(payStateQuery);
            threadpayStateQuery.Start(); // 直接传递参数给DoWork方法
        }
        void payStateQuery()
        {
            payStateRes = -999;
            PayStateMsg = "";
            try
            {
                ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();
                QRPayQueryInput requreInput = new QRPayQueryInput();
                requreInput.OutTradeNo = label1Age.Text;
                requreInput.TradeNo = "";
                requreInput.PayMoney = label1.Text;
                requreInput.Terminal = "001";
                requreInput.FacePay = false;
                if (radioButton2.Checked)
                {
                    requreInput.PayType = EnumQRPay.alipay;
                }
                else
                {
                    requreInput.PayType = EnumQRPay.weixin;
                }
                QRPayQueryOutput outputQueryState = clientService.QRPayQueryRequest(requreInput);
                if (outputQueryState.Result != null && outputQueryState.Result == "0")
                {
                    DateTime dateTime = DateTime.Now;
                    if (requreInput.PayType == EnumQRPay.weixin)
                    {
                        dateTime = DateTime.ParseExact(outputQueryState.PaymentTime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
                    }
                    else if (requreInput.PayType == EnumQRPay.alipay)
                    {
                        dateTime = DateTime.ParseExact(outputQueryState.PaymentTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        dateTime = DateTime.ParseExact(outputQueryState.PaymentTime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
                    }                      

                    if (dateTime.ToString("yyyyMMdd") == DateTime.Now.ToString("yyyyMMdd"))
                    {
                        if (!string.IsNullOrEmpty(outputQueryState.OutTradeNo) && !string.IsNullOrEmpty(outputQueryState.TradeNo))
                        {
                            sqlServer.UpdateOrderMsg(labelhzid.Text, requreInput.OutTradeNo, outputQueryState.TradeNo, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "1", userData.user_id);
                            string Balance = "";
                            int res = deposit_userDeposit(outputQueryState, ref Balance);
                            if (res == 0)
                            {
                                sqlServer.AddrechargeMsg(labelhzid.Text, labelName.Text, PatientIDCardNO.Text, requreInput.OutTradeNo, outputQueryState.TotalAmount, outputQueryState.TradeNo, userData.user_id);
                                PayStateMsg = Balance;
                                payStateRes = 0;
                            }
                            else
                            {
                                sqlServer.UpdateOrderMsg(labelhzid.Text, requreInput.OutTradeNo, outputQueryState.TradeNo, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "2", userData.user_id);
                                PayStateMsg = "收款成功，但充值失败！";
                                payStateRes = -1;
                            }

                        }
                        else
                        {
                            PayStateMsg = "查询支付状态成功：未支付";
                            payStateRes = -1;
                        }
                    }
                    else
                    {
                        PayStateMsg = "费用已跨天，无法进行补充充值！";
                        payStateRes = -1;
                    }
                }
                else
                {
                    PayStateMsg = "状态查询失败！" + outputQueryState.Message;
                    payStateRes = -1;
                }
            }
            catch (Exception ex) 
            {
                PayStateMsg = "查询失败！异常" + ex.Message.ToString();
                payStateRes = -1;
            }
            if (this.Created)
            {
                this.BeginInvoke(this.invokepayStateQuery);
            }
        }

        void updateFromPayStateQuery()
        {
            cmd.HideOpaqueLayer();
            if (payStateRes == 0)
            {
                string msg = "补充值后余额：" + PayStateMsg;
                MessageBox.Show(msg);
                getOrderInfo();
                this.textBox1.Focus();
                //this.OutTradeNo.Text = "";
                //MessageBox.Show("充值成功");
            }
            else
            {
                MessageBox.Show(PayStateMsg);
            }
        }
        /// <summary>
        /// 门诊充值
        /// </summary>
        /// <param name="outputQueryState"></param>
        /// <returns></returns>
        public int deposit_userDeposit(QRPayQueryOutput outputQueryState, ref string Balance)
        {
            try
            {
                ServiceRef.HospitalService_XXXXClient clientService = new HospitalService_XXXXClient();
                ServiceRef.DoPrepayIn inDeposit = new ServiceRef.DoPrepayIn();
                inDeposit.Key = "001";
                string Serial = "";
                ServiceRef.ResultBase reslut = new ServiceRef.ResultBase();
                reslut = clientService.GenerateSN();
                if (reslut != null)
                {
                    Serial = reslut.ReturnValue.ToString();
                }
                inDeposit.Serial = Serial;
                if (outputQueryState.TradeNo.Substring(0, 4) == "4200")
                {
                    inDeposit.PayMode = "7";
                }
                else
                {
                    inDeposit.PayMode = "6";
                }
                inDeposit.Amount = outputQueryState.TotalAmount;
                inDeposit.CashCount = outputQueryState.TotalAmount;
                #region 支付信息

                inDeposit.PayAccount = outputQueryState.PaymentAmount;
                inDeposit.PosSerial = outputQueryState.TradeNo;
                inDeposit.ReferenceNo = outputQueryState.OutTradeNo;
                #endregion
                //个人信息
                inDeposit.CardNO = orderitem.CardNO;
                inDeposit.PatientIDCardNo = orderitem.patientIdCardNo;
                inDeposit.PatientID = orderitem.patientId;
                inDeposit.PatientName = orderitem.PatientName;
                inDeposit.TerminalCode = "001";

                operateLog.WriteLog("充值执行开始");
                operateLog.WriteLog("操作员ID：" + userData.user_id);
                operateLog.WriteLog("操作员姓名：" + userData.user_name);
                operateLog.WriteLog("患者ID：" + orderitem.patientId);
                operateLog.WriteLog("患者卡号：" + orderitem.CardNO);
                operateLog.WriteLog("患者姓名：" + orderitem.PatientName);
                operateLog.WriteLog("订单号：" + outputQueryState.TradeNo);
                operateLog.WriteLog("订单金额：" + outputQueryState.TotalAmount);
                operateLog.WriteLog("流水号：" + outputQueryState.OutTradeNo);
                #region //卡类型赋值
                inDeposit.CardTypeID = "1";
                #endregion

                //this.BeginSaveAction();
                ServiceRef.DoPrepayOut payrecArray = clientService.DoPrepay(inDeposit);

                if (payrecArray != null)
                {
                    if (payrecArray.Result == "0")
                    {
                        Balance = payrecArray.Balance;
                        //this.EndSaveAction();
                        //outParam.inPerson.banlance = payrecArray.Balance;
                        //outParam.outDepositRes.accBalance = payrecArray.Balance;
                        //outParam.outDepositRes.serialNo = payrecArray.TranFlow;
                        //outParam.outDepositRes.updateTime = payrecArray.TranTime;

                        return 0;
                    }
                    else
                    {
                        return -1;
                    }
                }
                else
                {
                    return -1;
                }
            }
            catch
            {
                return -2;
            }
        }

        private void PayMsg_Load(object sender, EventArgs e)
        {
            this.textBox1.Focus();
        }

        private void PayMsg_Activated(object sender, EventArgs e)
        {
            this.textBox1.Focus();
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.button2_Click(sender, e);
            }
        }
    }
}
